<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Models\Post;
use App\Models\Comment;
use App\Models\PointLog;
use App\Http\Resources\PostResource;
use App\Http\Resources\PostInfoResource;
use App\Http\Resources\CommentResource;
use App\Http\Requests\PostRequest;
use App\Http\Requests\CommentRequest;
use App\Http\Requests\UpdatePostRequest;
use Intervention\Image\ImageManagerStatic as Image;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Storage;
use Vinkla\Hashids\Facades\Hashids;


class PostController extends Controller
{
    //
    public function index(Request $request){

        $user = $request->user();

        $q = $request->get('q');
        if($q){ //检查用户输入内容是否合法
            $app = \EasyWeChat\Factory::MiniProgram(config('wechat.mini_program.default'));
            $result = $app->content_security->checkText($q);
            if($result['errcode']){ //返回错误     
                return response()->json([]);
            }

        }

        $sort = $request->get('orderby');
        $sort = $sort == 'rank'?'rank':'id';
        $limit = intval($request->get('limit'));
        $limit =  $limit>5&&$limit<51?$limit:15;
        $cateid = intval($request->get('cateid'));

        //todo 管理员可以看到所有帖子
        if(config('cms.strict_audit')){ // 严格审核状态（用户只能看到自己发布的帖子和已经通过审核的帖子）
            $uid = $user->id;
            if($q){ //如果有关键字用有搜索功能的
                // 全文搜索不兼容 in写法，所以只查已审核的
                if($cateid){ 
                    $data = Post::search($q)->where('category_id',$cateid)->where('check_id',0)->orderBy($sort, 'desc')->paginate($limit); //simplePaginate
                }else{
                    $data = Post::search($q)->where('check_id',0)->orderBy($sort,'desc')->paginate($limit); //simplePaginate
                }
            }else{
                $data = Post::with('user','category')->whereIn('check_id',[0,1,$uid])->whereCate($cateid)->orderBy($sort, 'desc')->paginate($limit); //simplePaginate
            }

        }else{
            if($q){ //如果有关键字用有搜索功能的
                if($cateid){
                    $data = Post::search($q)->where('category_id',$cateid)->orderBy($sort, 'desc')->paginate($limit); //simplePaginate
                }else{
                    $data = Post::search($q)->orderBy($sort,'desc')->paginate($limit); //simplePaginate
                }
            }else{
                $data = Post::with('user','category')->whereCate($cateid)->orderBy($sort, 'desc')->paginate($limit); //simplePaginate
            }
        }
        return response()->json(PostResource::collection($data));
    }

    public function comments($id,Request $request){
        $sort = $request->get('orderby');
        $sort = $sort == 'rank'?'rank':'id';
        $limit = intval($request->get('limit'));
        $limit =  $limit>5&&$limit<51?$limit:15;
        $data = Comment::with('user')->where('post_id',$id)->orderBy($sort,'desc')->simplePaginate($limit);
        return response()->json(CommentResource::collection( $data ));
    }

    public function createPost(PostRequest $request){
        $app = \EasyWeChat\Factory::MiniProgram(config('wechat.mini_program.default'));
        $check_text = $request->get('body').' '
        .$request->get('video'); // 防测试贼
        
        $result = $app->content_security->checkText($check_text);
        if($result['errcode']){ //返回错误     
            return response()->json( [
                'err'=>1, 
                'msg'=>'含非法内容',
            ]);
        }

        $user = $request->user();
        $post = new Post;
        $post->category_id = intval($request->get('cateid'));
        $post->body = $request->get('body');
        $post->images = explode(',',$request->get('images'));
        $post->user_id = $user->id;
        $post->check_id = $user->id;
        $post->rank = 0;
        $post->liked = 0;
        $post->commented = 0;
        $post->video = $request->get('video'); // 如果有这个字段，作为视频类处理
        $post->save();
        return response()->json( [
            'err'=>0, 
            'msg'=>'发布成功'
        ]); 
    }

    
    public function updatePost(UpdatePostRequest $request){
        $user = $request->user();
        $app = \EasyWeChat\Factory::MiniProgram(config('wechat.mini_program.default'));
        $check_text = $request->get('body');
        $result = $app->content_security->checkText($check_text);
        if($result['errcode']){ //返回错误     
            return response()->json( [
                'err'=>1, 
                'msg'=>'含非法内容',
            ]);
        }

        $post = Post::findOrFail( intval($request->get('id')) );

        if( $post->user_id != $user->id){ //  这个验证只能自己改自己的（有机器人爬改内容），请自行拓展管理员可改所有。
            return response()->json( [
                'err'=>1, 
                'msg'=>'修改失败'
            ]); 
        }

        $post->category_id = intval($request->get('cateid'));
        $post->body = $request->get('body');
        $post->video = $request->get('video');
        $post->images = explode(',',$request->get('images'));
        $post->user_id = $user->id;
        $post->check_id = $user->id;
        $post->save();
       
        return response()->json( [
            'err'=>0, 
            'msg'=>'修改成功'
        ]); 
    }

    public function newComment($id,CommentRequest $request){

        $app = \EasyWeChat\Factory::MiniProgram(config('wechat.mini_program.default'));
       
        $body = $request->get('body');
        $result = $app->content_security->checkText($body);
        if($result['errcode']){ //返回错误     
            return response()->json( [
                'err'=>1, 
                'msg'=>'含非法内容',
            ]);
        }

        $user = $request->user();
        $post = Post::findOrFail($id);
        // dd($comment);
        $reply_id = intval($request->get('reply_id'));
        $new_comment = new Comment;
        $new_comment->post_id = $id;
        $new_comment->user_id = $user->id;
        $new_comment->check_id = $user->id;
        $new_comment->reply_id = $reply_id;
        $new_comment->body = $body;
        $new_comment->liked = 0;
        $new_comment->commented = 0;
        $new_comment->rank = 0;
        $new_comment->save();
        if($reply_id){
            $quote = $new_comment->quote;
            $quote->commented ++;
            $mt_time =  strtotime( $quote->created_at->format('Y-m-d') ) - strtotime('2019-05-01');
            $quote->rank = $this->rank( $quote->liked, $quote->commented, $mt_time);
            $quote->save();
        }
        $post->commented ++;
        $mt_time =  strtotime( $post->created_at->format('Y-m-d') ) - strtotime('2019-05-01'); 
        $post->rank = $this->rank( $post->liked, $post->commented, $mt_time);
        $post->save();
        return response()->json(new CommentResource($new_comment));

    }
    
    
    public function info($id,Request $request){
        $data = Post::findOrFail($id);
        // 补丁，处理没有图片时返回第一个键值为空的
        if(count($data->images) == 1 && !$data->images[0])  $data->images = [];
        return response()->json($data);
    }

    public function show($id,Request $request){
        $data = Post::findOrFail($id);
        $data->pageview++;
        $data->save();
        return response()->json(new PostInfoResource( $data ));
    }

    public function del($id,Request $request){
        $user = $request->user();
        $post = Post::findOrFail($id);
        if( $post->user_id != $user->id){ //  这个验证只能自己删除自己的（有机器人爬改内容），请自行拓展管理员可删除所有。
            return response()->json( [
                'err'=>1, 
                'msg'=>'删除失败'
            ]); 
        }
        $post->delete();
        return response()->json( [
            'err'=>0, 
            'msg'=>'删除成功'
        ]); 
    }

    
    public function like($id,Request $request){
        $user = $request->user();
        $data = Post::findOrFail($id);
        if(!$user->hasLiked($data)){
            $user->like($data);
            $data->liked ++;
            // 排序等于喜欢人数+认同人数+否定人数(暂时性的)
            $mt_time =  strtotime( $data->created_at->format('Y-m-d') ) - strtotime('2019-05-01');
            $data->rank = $this->rank( $data->liked, $data->commented, $mt_time);
            $data->save();
        }
        return response()->json(['ok']);
    }
    
    public function unlike($id,Request $request){
        $user = $request->user();
        $data = Post::findOrFail($id);
        if($user->hasLiked($data)){
            $user->unlike($data);
            $data->liked --;
            // 排序等于喜欢人数+认同人数+否定人数(暂时性的)
            // 间隔
            $mt_time =  strtotime( $data->created_at->format('Y-m-d') ) - strtotime('2019-05-01');
            $data->rank = $this->rank( $data->liked, $data->commented, $mt_time);
            $data->save();
        }
        return response()->json(['ok']);
    }


    
    
    public function getPoster($uid,$id,Request $request){
        // 参考这里优化 https://github.com/Intervention/imagecache
      $user = User::findOrFail($uid);
      $post = Post::findOrFail($id);
      $img = Image::canvas(600, 600, '#ffffff');


      $share_cover = $post->images && $post->images[0]?$post->images[0]:'';

      $cover = !$share_cover || URL::isValidUrl($share_cover)?$share_cover:Storage::disk(config('admin.upload.disk'))->url($share_cover);
      
        //   dd($cover);
      if($cover){
        // todo 优化，解决图片不存在的bug
        if(preg_match("/\/(\d+)\//u",$cover,$res)){
            $cover = strtr($cover,['.com/'=>'.com/'.$post->user_id.'/'.Hashids::encode($post->user_id,intval($res[1])).'/']);
        }
        $img3 = Image::make($cover);

        $img3w = $img3->width();
        $img3h = $img3->height();

        $blh = ($img3h / 4 * 5) > $img3w; 
        if(!$blh){ //宽图先缩高为480
            $img3->resize(null, 480, function ($constraint) {
                $constraint->aspectRatio();
            });
        }else{ // 高图先缩宽为 600
            $img3->resize(600, null, function ($constraint) {
                $constraint->aspectRatio();
            });
        }
        $img3->crop(600, 480); // 上面是为了把图标裁剪出合适的大小，套成海报中

        $img->insert($img3, 'top-left',0,0);
      }

      
      $username = $user->name?$user->name:'我';
      $img->text(str_limit($username.'分享了一个帖子',44),80,510, function($font) { // 这里需要优化
          $font->file(storage_path('font.ttf'));
          $font->size(24);
          $font->color('#000000');
          $font->valign('top');
      });


      
      // 用户头像
      $img1 = Image::make($user->avatar);
      $img1->resize(40, 40);
      $img->insert($img1, 'top-left',20,502);

      //todo 这里需要优化，如果你需要把视频和图文分开不同的详情页，需要对这里进行区分
      $img2 = Image::make(url('/api/qrcode?uid='.$uid.'&postid='.$id));
      $img2->resize(100, 100);
      $img->insert($img2, 'bottom-right',50,10);

      $img->text('长按识别二维码查看',80,550, function($font) {
          $font->file(storage_path('font.ttf'));
          $font->size(18);
          $font->color('#000000');
          $font->valign('top');
      });

      return  $img->response();
  }

     /**
     * 实现近期热门排序 （自己去了解这个算法有什么用）
     * @param int $vote 支持
     * @param int $devote 反对
     * @param bool $time  创建项目时间差 
     * @return float
     */
    function rank($liked = 100, $commented = 99, $time = false){
        $socre = log10($liked + $commented *2 ) +  $time / 86400; // 建议值为 45000;
        return intval($socre * 1000);
    }
}
